package com.xiaodong.config;

import java.util.concurrent.LinkedBlockingDeque;

/**
 * @author hzd
 * @date 2024/1/4 18:33
 */
public class LeakyBucketLimiter {
  private LinkedBlockingDeque<Character> bucketBlockingDeque;

  // 消费速率 request/s
  private Integer rate;

  public LeakyBucketLimiter(Integer rate){
    this.rate = rate;
  }
  public LeakyBucketLimiter(Integer rate, Integer maxRequestNum){
    this.rate = rate;
    this.bucketBlockingDeque = new LinkedBlockingDeque(maxRequestNum);
  }

  // 消费漏桶的水
  public boolean tryAcquire(){
    boolean flag = bucketBlockingDeque.offer('A');
    if (!flag){
      return flag;
    }

    new Thread(()->{
      while (!bucketBlockingDeque.isEmpty()){
        bucketBlockingDeque.pop();

        try {
          Thread.sleep(rate * 1000);
        } catch (InterruptedException e) {
          throw new RuntimeException(e);
        }
      }
    },"bucketThreadName");

    return flag;
  }

  public static void main(String[] args) {
    LeakyBucketLimiter leakyBucketLimiter = new LeakyBucketLimiter(1, 5);
    for (int i = 0; i < 10; i++) {
      boolean b = leakyBucketLimiter.tryAcquire();

      if (b){
        System.out.println("执行接口成功!");
      }
      if (!b){
        System.out.println("被限流了!");
      }
    }
  }

}
